package p.ithorns.integration.hz.cluster;

import com.hazelcast.config.*;
import com.hazelcast.core.Hazelcast;

/**
 * HazelcastClusterApp
 * TODO ithorns
 *
 * @author Ht.L
 * @date 2023-11-21 09:17
 * @since 1.0.0
 */
public class HazelcastClusterApp {
    public static void main(String[] args) {

        new Thread(() -> {
            Config config = new Config();
            config.setInstanceName("hz-instance");
            config.setClusterName("my-hazelcast");

            NetworkConfig networkConfig = config.getNetworkConfig();
            networkConfig.setPortAutoIncrement(true);

            JoinConfig joinConfig = networkConfig.getJoin();
            joinConfig.getMulticastConfig().setEnabled(false);
            joinConfig.getTcpIpConfig().setEnabled(true).addMember("127.0.0.1");

            MemberAttributeConfig mac = new MemberAttributeConfig();
            mac.setAttribute("type", "worker");
            config.setMemberAttributeConfig(mac);

            Hazelcast.newHazelcastInstance(config);

            // 阻塞线程，保持集群运行
            synchronized (HazelcastClusterApp.class) {
                try {
                    HazelcastClusterApp.class.wait();
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
            }
        }).start();

        // 当需要关闭集群时，调用以下代码
        synchronized (HazelcastClusterApp.class) {
            HazelcastClusterApp.class.notify();
        }
    }
}